import time

from selenium.webdriver import Keys

from PO项目实战.对象层.iframe_page import IframePage


class IframeBusiness(IframePage):
    
    def __init__(self, driver):
        super().__init__(driver)

    # 打开用户管理页面
    def open_iframe_page(self):
        self.driver.get(self.url)

    # 切换到iframe
    def switch_to_iframe(self):
        self.driver.switch_to.frame(self.iframe_ele)

    # 点击回车键进行查询
    def search_something(self, lizi_input):
        self.search_input_ele.send_keys(lizi_input)
        self.search_input_ele.send_keys(Keys.ENTER)

    # 切换到新新窗口
    def switch_to_window(self, title):
        flag = False
        # 获取窗口句柄
        handles = self.driver.window_handles
        for handle in handles:
            # 切换窗口
            self.driver.switch_to.window(handle)
            # 根据title判断切换窗口是否是所需要的
            if title in self.driver.s_title:
                flag = True
                # 限制对 Google 网址的访问
                block_google_script = """
                document.addEventListener("DOMContentLoaded", function() {
                    window.addEventListener('beforeunload', function() {
                        var googleLinks = document.getElementsByTagName('a');
                        for (var i = 0; i < googleLinks.length; i++) {
                            if (googleLinks[i].hostname === 'google.com') {
                                googleLinks[i].href = "#";
                            }
                        }
                    });
                });
                """
                self.driver.execute_script(block_google_script)
                break
            else:
                continue
        if flag:
            pass
        else:
            print("切换窗口失败，窗口 {} 不存在！".format(title))

    # 获取第一条查询结果
    def get_first_data(self):
        text =self.first_data_ele.get_attribute("innerText")
        return text

    # 控制页面加载时间
    def page_timeout_control(self, second=10):
        self.driver.set_page_load_timeout(second)


